﻿using System;
using System.Collections.Generic;
using System.Linq;
using NOSDC.Pocos;
using NOSDC.Entities;
using System.Data.Objects;

namespace NOSDC.Repositories.Jobs
{
    public sealed class JobRepository : IJobRepository
    {       
        private readonly NOSDCContext _context;

        public JobRepository()
        {
            _context = new NOSDCContext();
        }

        public void PostJob(Job job)
        {
            _context.Jobs.AddObject(job);
            _context.SaveChanges();
        }

        public IList<Job> GetActiveJobs(bool includeInactiveAtBottom = false)
        {
            var jobs = _context.Jobs.Where(job => job.DateExpires > DateTime.Now).ToList();
       
            if(includeInactiveAtBottom)
            {
                var inactiveJobs = _context.Jobs.Where(job => job.DateExpires < DateTime.Now);
                jobs.AddRange(inactiveJobs);
            }

            return jobs;
        }

        public void UpdateJob(Job job)
        {
            _context.Jobs.Attach(job);
            var jobEntry = _context.ObjectStateManager.GetObjectStateEntry(job);
            jobEntry.SetModified();
            _context.ObjectStateManager.ChangeObjectState(job, System.Data.EntityState.Modified);
            _context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
        }

        public void DeleteJob(Job job)
        {
            _context.DeleteObject(job);
            _context.SaveChanges();
        }

        public Job GetJobById(int id)
        {
            return _context.Jobs.FirstOrDefault(job => job.Id == id);
        }

        public IEnumerable<Job> GetRecentJobs()
        {
            return _context.Jobs.Where(job => job.DatePosted <= DateTime.Now && job.DateExpires >= DateTime.Now).OrderByDescending(job => job.DatePosted);
        }
    }
}
